/**
 * Cypress 测试运行脚本
 * 提供不同的测试运行选项和报告生成
 */
const { spawn } = require('child_process')
const path = require('path')

// 测试配置
const testConfigs = {
  smoke: {
    spec: 'cypress/e2e/test-suite.cy.ts',
    description: '冒烟测试 - 快速验证核心功能'
  },
  full: {
    spec: 'cypress/e2e/**/*.cy.ts',
    description: '完整测试套件 - 所有端到端测试'
  },
  gameFlow: {
    spec: 'cypress/e2e/game-flow.cy.ts',
    description: '游戏流程测试'
  },
  controls: {
    spec: 'cypress/e2e/game-controls.cy.ts',
    description: '游戏控制测试'
  },
  character: {
    spec: 'cypress/e2e/character-selection.cy.ts',
    description: '角色选择测试'
  },
  settings: {
    spec: 'cypress/e2e/settings-preferences.cy.ts',
    description: '设置和偏好测试'
  },
  achievements: {
    spec: 'cypress/e2e/achievements-leaderboard.cy.ts',
    description: '成就和排行榜测试'
  },
  performance: {
    spec: 'cypress/e2e/performance-error-handling.cy.ts',
    description: '性能和错误处理测试'
  },
  responsive: {
    spec: 'cypress/e2e/responsive-compatibility.cy.ts',
    description: '响应式设计和兼容性测试'
  }
}

/**
 * 运行指定的测试套件
 * @param {string} testType - 测试类型
 * @param {object} options - 运行选项
 */
function runTests(testType = 'smoke', options = {}) {
  const config = testConfigs[testType]
  
  if (!config) {
    console.error(`未知的测试类型: ${testType}`)
    console.log('可用的测试类型:')
    Object.keys(testConfigs).forEach(key => {
      console.log(`  ${key}: ${testConfigs[key].description}`)
    })
    process.exit(1)
  }

  console.log(`\n🚀 开始运行: ${config.description}`)
  console.log(`📁 测试文件: ${config.spec}\n`)

  const cypressArgs = [
    'run',
    '--spec', config.spec
  ]

  // 添加额外选项
  if (options.headless !== false) {
    cypressArgs.push('--headless')
  }

  if (options.browser) {
    cypressArgs.push('--browser', options.browser)
  }

  if (options.record) {
    cypressArgs.push('--record')
  }

  if (options.parallel) {
    cypressArgs.push('--parallel')
  }

  // 运行 Cypress
  const cypress = spawn('npx', ['cypress', ...cypressArgs], {
    stdio: 'inherit',
    cwd: process.cwd()
  })

  cypress.on('close', (code) => {
    if (code === 0) {
      console.log(`\n✅ 测试完成: ${config.description}`)
    } else {
      console.log(`\n❌ 测试失败: ${config.description}`)
      process.exit(code)
    }
  })

  cypress.on('error', (error) => {
    console.error('运行测试时出错:', error)
    process.exit(1)
  })
}

/**
 * 解析命令行参数
 */
function parseArgs() {
  const args = process.argv.slice(2)
  const testType = args[0] || 'smoke'
  
  const options = {
    headless: !args.includes('--headed'),
    browser: args.includes('--chrome') ? 'chrome' : 
             args.includes('--firefox') ? 'firefox' : 
             args.includes('--edge') ? 'edge' : null,
    record: args.includes('--record'),
    parallel: args.includes('--parallel')
  }

  return { testType, options }
}

// 主程序
if (require.main === module) {
  const { testType, options } = parseArgs()
  runTests(testType, options)
}

module.exports = { runTests, testConfigs }